<template>
  <div class="messages-item">
    <!-- 问题 -->
    <div class="chat-message is-own" v-if="!currentMessage.isAnswer">
      <div class="message-content">
        <ChatFiles :files="currentMessage.message_files" />
        <div class="message-bubble">
          <div class="message-text">
            <div v-html="currentMessage.content"></div>
          </div>
        </div>
        <div class="user-btn">
          <el-button type="" link @click="handleCopy(currentMessage)">
            <el-icon :size="16">
              <CopyDocument />
            </el-icon>
          </el-button>
          <el-button type="" link @click="handleEdit(currentMessage)">
            <el-icon :size="16">
              <EditPen />
            </el-icon>
          </el-button>
        </div>
      </div>
      <div class="message-avatar">
        <img src="@/assets/images/chat/profile.jpg" alt="">
      </div>
    </div>
    <!-- 回答 -->
    <div v-if="currentMessage.isAnswer">
      <div class="chat-message">
        <!-- <div class="message-avatar">
          <img src="@/assets/images/chat/ai_logo.png" alt="">
        </div> -->
        <div class="message-content">
          <ChatThink :parsed="parsedContent" :message="currentMessage" :is-streaming="isStreaming"
            :thinkTime="formattedThinkTime" />
          <div class="message-bubble" v-if="parsedContent.visibleContent">
            <div class="message-text">
              <MarkdownView :content="parsedContent.visibleContent" />
            </div>
          </div>
          <ChatQuote v-if="currentMessage.retriever_resources && currentMessage.retriever_resources.length > 0"
            :list="currentMessage.retriever_resources" />
        </div>
      </div>
      <!-- 只有当流式结束后才显示切换与重问按钮 -->
      <!-- <ChatSwitch :message="currentMessage" v-if="!isStreaming && currentMessage.siblingCount > 1"
        @switch="switchChild">
      </ChatSwitch> -->

      <div class="action-btn" v-if="isStreaming">
        <el-button v-if="currentMessage.content" class="refresh" @click="handleCopy(currentMessage)">
          <el-icon :size="14">
            <CopyDocument />
          </el-icon>&nbsp;复制
        </el-button>
        <el-button class="refresh" @click="handleRefresh(currentMessage)">
          <el-icon :size="14">
            <Refresh />
          </el-icon> &nbsp;重新生成
        </el-button>

      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { ref, computed, watch } from 'vue';
import { useClipboard } from "@vueuse/core";
import ChatQuote from "./ChatQuote.vue";
import MarkdownView from "./MarkdownView/index.vue";
import ChatThink from "./ChatThink.vue";
import ChatSwitch from "./ChatSwitch.vue";
import ChatFiles from "./ChatFiles.vue";
const emit = defineEmits(["switch", "refresh", 'edit']);
const { copy } = useClipboard(); // 初始化 copy 到粘贴板
const props = defineProps({
  message: {
    type: Object,
    required: true,
    default: () => ({}),
  },
  isStreaming: {
    type: Boolean,
    default: false,
  },
});

// 获取当前要显示的消息（原始消息或当前选中的子消息）
const currentMessage = computed(() => props.message);

// 思考时间计时相关
const thinkStartTime = ref(null);
const thinkTime = ref(0);
const thinkTimer = ref(null);

// 格式化时间显示（保留一位小数的秒）
const formattedThinkTime = computed(() => {
  return `${thinkTime.value.toFixed(1)}`;
});

// 开始思考计时
const startThinkTimer = () => {
  if (thinkTimer.value) {
    clearInterval(thinkTimer.value);
  }
  thinkStartTime.value = new Date();
  thinkTimer.value = setInterval(() => {
    if (thinkStartTime.value) {
      thinkTime.value = ((new Date() - thinkStartTime.value) / 1000);
    }
  }, 100);
};

// 停止思考计时
const stopThinkTimer = () => {
  if (thinkTimer.value) {
    clearInterval(thinkTimer.value);
    thinkTimer.value = null;
  }
};

// 重置思考计时
const resetThinkTimer = () => {
  stopThinkTimer();
  thinkTime.value = 0;
  thinkStartTime.value = null;
};

// 定义parsedContent计算属性
const parsedContent = computed(() => {
  const raw = (currentMessage.value?.content || "").toString();
  if (!raw) return { visibleContent: "", thinkContent: "", hasThink: false, thinkCompleted: false };

  const openTag = "<think>";
  const closeTag = "</think>";

  let cursor = 0;
  let visibleBuilder = "";
  const thinkParts = [];
  let hasUnclosedTag = false;

  while (cursor < raw.length) {
    const openIdx = raw.indexOf(openTag, cursor);
    if (openIdx === -1) {
      visibleBuilder += raw.slice(cursor);
      break;
    }
    visibleBuilder += raw.slice(cursor, openIdx);
    const afterOpen = openIdx + openTag.length;
    const closeIdx = raw.indexOf(closeTag, afterOpen);
    if (closeIdx === -1) {
      thinkParts.push(raw.slice(afterOpen));
      hasUnclosedTag = true;
      cursor = raw.length;
      break;
    } else {
      thinkParts.push(raw.slice(afterOpen, closeIdx));
      cursor = closeIdx + closeTag.length;
      continue;
    }
  }

  const thinkContent = thinkParts.join("\n\n").trim();
  const thinkCompleted = !hasUnclosedTag && raw.includes(openTag);

  return {
    visibleContent: visibleBuilder.trim(),
    thinkContent,
    hasThink: raw.includes(openTag),
    thinkCompleted,
    hasUnclosedTag
  };
});

// 监听流式状态、思考内容和思考完成状态，控制计时器
watch(
  [() => !props.isStreaming,
  () => parsedContent.value.hasThink,
  () => parsedContent.value.thinkCompleted],
  ([newStreamingVal, hasThink, thinkCompleted]) => {
    if (newStreamingVal && hasThink && !thinkCompleted) {
      resetThinkTimer();
      startThinkTimer();
    } else if (thinkCompleted) {
      stopThinkTimer();
    }
  },
  { immediate: true }
);

watch(() => props.isStreaming, (newVal) => {
  if (newVal) {
    stopThinkTimer();
  }
});

// 监听消息ID变化，重置计时器
watch(
  () => props.message?.id,
  () => {
    resetThinkTimer();
  }
);

// 切换到指定子消息
const switchChild = (id) => {
  emit("switch", id);
};

const handleRefresh = (message) => {
  emit("refresh", message);
};


const handleCopy = (message) => {
  const content = message.content || "";
  copy(content);
  ElMessage({
    message: '复制成功!',
    grouping: true,
    type: 'success',
  })
};

const handleEdit = (message) => {
  emit("edit", message);
};



</script>

<style scoped lang="scss">
.messages-item {
  padding-bottom: 40px;

  .chat-message {
    display: flex;
    margin-bottom: 5px;
    align-items: flex-start;
    position: relative;
    padding-right: 45px;

    .user-btn {
      margin-top: 8px;
      opacity: 0;
    }

    .message-avatar {
      flex-shrink: 0;

      img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
      }
    }

    .message-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: flex-start;

      .message-bubble {
        border-radius: 10px;
        padding: 5px 12px 0px;
        position: relative;
        word-wrap: break-word;


        .message-text {
          :deep(br) {
            line-height: 1.4;
          }
        }
      }
    }

    &.is-own {
      justify-content: end;
      padding-right: 0;
      .message-content {
        align-items: flex-end;
      }

      .message-avatar {
        margin-left: 8px;
      }

      .message-bubble {
        background: #EEF5FF;
        padding: 10px 16px;
      }

      &:hover {
        .user-btn {
          opacity: 1;
        }
      }
    }
  }

  .action-btn {
    display: flex;
    justify-content: flex-end;
    padding-right: 45px;
    opacity: 0;
    transition: opacity 0.3s ease;

    .refresh {
      border-radius: 6px;
    }
  }

  &:hover {
    .action-btn {
      opacity: 1;
    }
  }
}

@keyframes messageSlideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .chat-message {
    .message-content {
      max-width: 80%;
    }
  }
}
</style>
